/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.business.customer.core.repository.service;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import info.peigen.hotpot.business.account.core.domain.account.Account;
import info.peigen.hotpot.business.account.core.repository.service.AccountRepository;
import info.peigen.hotpot.business.customer.core.domain.partner.Partner;
import info.peigen.hotpot.business.customer.core.domain.partner.action.PartnerConverter;
import info.peigen.hotpot.business.customer.core.repository.entity.PartnerEntity;
import info.peigen.hotpot.business.customer.core.repository.mapper.PartnerMapper;
import info.peigen.hotpot.common.core.result.ResultCode;
import info.peigen.hotpot.common.service.base.exception.BusinessException;
import info.peigen.hotpot.component.data.repository.beetlsql.service.AbstractBeetlSqlWithoutPartnerIdRepository;
import org.beetl.sql.core.query.Query;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import java.util.List;

/**
 * <b>(PartnerRepository)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2021/8/5
 */
@Component
public class PartnerRepository extends AbstractBeetlSqlWithoutPartnerIdRepository<PartnerMapper, PartnerEntity> {
    @Inject
    AccountRepository accountRepository;

    public Partner active(String partnerId) {
        PartnerEntity entity               = getMapper().findByPartnerId(partnerId);
        Account       intermediateAccounts = accountRepository.active(partnerId);
        Account       selfAccounts         = accountRepository.active(partnerId);
        return PartnerConverter.convert(entity).setIntermediateAccount(intermediateAccounts).setSelfAccount(selfAccounts);
    }

    public List<PartnerEntity> select(String name) {
        return getMapper().getSQLManager().lambdaQuery(PartnerEntity.class).andLike("partner_name", "%" + name + "%").orEq("abbreviation", name).select();
    }

    public void store(Partner partner) {
        saveOrUpdate(PartnerConverter.convert(partner));
    }


    public Partner lock(String partnerId) {
        Assert.isTrue(StrUtil.isNotEmpty(partnerId), () -> new BusinessException(ResultCode.FAILURE, "加锁时[partnerId]不得为空!"));
        return PartnerConverter.convert(getMapper().lockByPartnerId(partnerId));
    }

    public List<PartnerEntity> listByPartnerId(List<String> partnerIds) {
        return getMapper().createLambdaQuery()
                .andIn(PartnerEntity::getPartnerId, Query.filterNull(partnerIds))
                .select();
    }
}